package com.xgp.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 懒汉式
 */
public class LazyMan {

    private LazyMan() {

        synchronized (LazyMan.class) {
            synchronized (LazyMan.class) {
                if(lazyMan != null) {
                    throw new RuntimeException("=============");
                }
            }
        }

        System.out.println(Thread.currentThread().getName() + " ok");
    }

    private volatile static LazyMan lazyMan;

    //双重检测
    public static LazyMan getInstance() {
        if(lazyMan == null) {
            synchronized (LazyMan.class) {
                if(lazyMan == null) {
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }

/*    public static void main(String[] args) {
        for(int i = 0;i < 10;i++){
            new Thread(() -> {
                LazyMan.getInstance();
            }).start();
        }
    }*/

    /**
     * 反射破坏
     * @param args
     */
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan lazyMan = LazyMan.getInstance();
        Constructor<LazyMan> fanshe = LazyMan.class.getDeclaredConstructor(null);

        fanshe.setAccessible(true);

        LazyMan lazyMan2 = fanshe.newInstance();

        System.out.println(lazyMan == lazyMan2);
    }
}
